package socket

import (
	"bufio"
	"fmt"
	"io"
	"net"
)

func processEcho(con net.Conn) {
	defer con.Close()

	for {
		var buf [128]byte
		n, err := con.Read(buf[:])
		if err != nil {
			fmt.Println("err=" + err.Error())
			break
		}

		recv := string(buf[:n])
		fmt.Println(recv)

		con.Write([]byte("from server: " + recv))
	}
}

func processMsg(con net.Conn) {
	defer con.Close()

	reader := bufio.NewReader(con)
	for {
		msg, err := Decode(reader)
		if err == io.EOF {
			fmt.Println("EOF")
			return
		}
		if err != nil {
			fmt.Println("decode msg error, " + err.Error())
			return
		}

		if len(msg) > 0 {
			fmt.Println(msg)
			response := "from server:" + msg

			data, _ := Encode(response)
			con.Write(data)
		}
	}
}

/**
goroutine per connection模式，在海量连接时，性能急剧下降，待改进
*/
func EchoServer() {
	listen, _ := net.Listen("tcp", "127.0.0.1:9000")
	fmt.Println("server started")

	for {
		conn, _ := listen.Accept()
		go processEcho(conn)
	}
}

/**
goroutine per connection模式，在海量连接时，性能急剧下降，待改进
*/
func PacketServer() {
	listen, _ := net.Listen("tcp", "127.0.0.1:9000")
	fmt.Println("packet server started")

	for {
		conn, _ := listen.Accept()
		go processMsg(conn)
	}
}
